package service

import (
	"context"
	"fmt"
	"go-admin/server/internal/repository"
	"go-admin/server/internal/service/sms"
	"go-admin/server/internal/service/sms/ratelimit"
	"math/rand"
	"time"
)

var (
	codeTplId = "1906931"
	//codeTplId = "SMS_462660905"
	// ErrCodeVerifyTooManyTimes = repository.ErrCodeVerifyTooManyTimes
	ErrCodeSendTooMany = repository.ErrCodeSendTooMany
	ErrRateLimit       = ratelimit.ErrRateLimit
)

//var codeTplId = "SMS_462660905"

//var codeTplId = "SMS_54320021"

type CodeService interface {
	Send(ctx context.Context, biz, phone string) error
	Verify(ctx context.Context, biz, code, phone string) (bool, error)
}

type codeService struct {
	repo   repository.CodeRepository
	smsSvc sms.Service
}

func NewCodeService(repo repository.CodeRepository, smsSvc sms.Service) CodeService {
	return &codeService{
		repo:   repo,
		smsSvc: smsSvc,
	}
}

func (svc *codeService) Send(ctx context.Context, biz, phone string) error {
	code := svc.generateCode()
	err := svc.repo.Store(ctx, biz, phone, code) //校验发送的频率  一分钟只能发一条
	if err != nil {
		return err
	}
	err = svc.smsSvc.Send(ctx, codeTplId, []string{code}, phone)
	//err = global.SMS.Send(ctx, codeTplId, []string{code}, phone)   全局变量实时获取数据的方式
	return err
}

func (svc *codeService) Verify(ctx context.Context, biz, code, phone string) (bool, error) {
	return svc.repo.Verify(ctx, biz, code, phone)
}

func (svc *codeService) generateCode() string {
	rand.Seed(time.Now().UnixNano())

	min := 100000 // 最小值为100000
	max := 999999 // 最大值为999999
	randomCode := rand.Intn(max-min+1) + min

	code := fmt.Sprintf("%06d", randomCode)
	return code
}
